﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using ESF.General;
using ESF.MSExcel;
using ESF.WinForms;
using ESF.Data;
using MessagingToolkit.Barcode;
using ESF.FileProcessing;
using Leadtools.Barcode;
using ESF.WinForms.Elements;
using ESF.General.GUI;
using ESF.Indexing;

#endregion


namespace ESF.FileHelper.Controls
{
	public partial class uscFolderGenerateIndex : BaseUserControl
	{
		#region Eventos

		public event Program.DelegateReturnMenu ReturningMenu;

		#endregion
		
		
		#region Miembros

		private IndexMaker _IndexMaker;

		#endregion


		#region Constructor
		
		public uscFolderGenerateIndex() : base ()
		{
			InitializeComponent ();

			chkBarcodeTypes.SetItemChecked (2, true);
			chkBarcodeTypes.SetItemChecked (6, true);

			_IndexMaker = new IndexMaker(ReportProgress);
			
			ddlExtension.SelectedIndex = 0;
			ddlPrefixBarCodeType.SelectedIndex = 6;
		}

		#endregion


		#region Funciones

		private void ReportProgress(string pMessage = "", int pTotalWorkCount = 0, int pReadyWorkCount = 0, int pTotalErrors = 0, long pItemElapsedMs = 0)
		{
			GUIHelper.SetAdvance(ProgressDialog, pMessage, pTotalWorkCount, pReadyWorkCount, pTotalErrors, pItemElapsedMs);
		}


		private delegate void EnableGUI (bool pEnabled, bool pCancelled);


		private void EnableBasicFeatures (bool pEnabled, bool pCancelled)
		{
			Invoke ((MethodInvoker) delegate () 
			{
				chkClearResults.Enabled = pEnabled;

				txtFolder.Enabled = pEnabled;
			
				btnGenerateIndex.Enabled = pEnabled;

				chkDetectBarcodes.Enabled = pEnabled;

				chkTakeOnlyFirst.Enabled = pEnabled;

				btnToXLS.Enabled = pEnabled;

				Cursor = Cursors.Arrow;

				if (pCancelled)
				{
					MessageBox.Show (this, "El procesamiento ha sido cancelado y su avance almacenado", "Tarea Cancelada", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				}

			});
		}
		
		#endregion


		#region Button Events

		private void btnReturnMenu_Click(object sender, EventArgs e)
		{
			if (ReturningMenu != null)
			{
				ReturningMenu ();
			}
		}

		#endregion


		#region Label Events

		private void lnkSelectFolder_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			if (fbdSelectFolder.ShowDialog (this) == DialogResult.OK)
			{
				txtFolder.Text = fbdSelectFolder.SelectedPath;
				return;
			}

			txtFolder.Text = string.Empty;
		}


		private void lnkIndexFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Process.Start (_IndexMaker.GeneratedExcelFileName);
		}

		#endregion

		
		#region Button Events

		private List<BarcodeSymbology> GetBarCodeSelected()
		{
			List<BarcodeSymbology> findBarcodeTypes = new List<BarcodeSymbology>();


			foreach (string itemName in chkBarcodeTypes.CheckedItems)
			{
				findBarcodeTypes.Add((BarcodeSymbology)Enum.Parse(typeof(BarcodeSymbology), itemName));
			}

			return findBarcodeTypes;
		}


		private void btnGenerateIndex_Click(object sender, EventArgs e)
		{
			List<string> validExtensions = new List<string> ();


			if (TextHelper.IsEmpty (txtIndexName.Text))
			{
				MessageBox.Show (this, "Diligencie el nombre del indice", "Parametros Invalidos", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			
			if (!Directory.Exists (txtFolder.Text))
			{
				MessageBox.Show (this, "La ruta diligenciada no existe", "Parametros Invalidos", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			lnkIndexFile.Visible = false;


			validExtensions.Add (ListLoader.GetSelectedValue <string> (ddlExtension));

			
			EnableBasicFeatures (false, false);

			ProgressDialog.HideWhenComplete = false;
			ProgressDialog.Show (ParentForm);
			ProgressDialog.Clear ();
			ProgressDialog.IsCancelable = true;
			
			try
			{
				_IndexMaker.Initialize(GetBarCodeSelected (), txtIndexName.Text, txtFolder.Text, chkClearResults.Checked, null, null, null, false);
			}
			catch (Exception pex)
			{
				LogError (pex);

				EnableBasicFeatures(true, false);

				return;
			}


			Task.Factory.StartNew (delegate () 
			{
				try
				{
					_IndexMaker.Generate (
						chkDetectBarcodes.Checked, chkOnlyFirstFileByFolder.Checked,
						validExtensions, 
						true, chkTakeOnlyFirst.Checked, chkUseWatcher.Checked);
				}
				catch (Exception pEx)
				{
					LogError (pEx);
				}
				finally
				{
					EnableBasicFeatures(true, false);
				}
			});
		}


		private void btnToXLS_Click(object sender, EventArgs e)
		{
			if (TextHelper.IsEmpty (txtIndexName.Text))
			{
				MessageBox.Show (this, "Diligencie el nombre del indice", "Parametros Invalidos", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}


			if (!Directory.Exists (txtFolder.Text))
			{
				MessageBox.Show (this, "Diligencie una ruta valida donde se almacenar el indice en Excel", "Parametros Invalidos", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			
			ProgressDialog.Show (ParentForm);
			ProgressDialog.Clear ();
			ProgressDialog.IsCancelable = false;
			

			try
			{
				_IndexMaker.Initialize (GetBarCodeSelected (), txtIndexName.Text, txtFolder.Text, false, ListLoader.GetSelectedValue<string> (ddlPrefixBarCodeType), txtSetPrefix.Text, txtItemPrefix.Text, chkUseBasicExcel.Checked);
			}
			catch (Exception pex)
			{
				LogError (pex);

				EnableBasicFeatures(true, false);

				return;
			}


			Task.Factory.StartNew (delegate () 
			{
				try
				{
					_IndexMaker.ConvertDBToXLS(ReportProgress); 
					
					WinFormsHelper.SetVisible (lnkIndexFile);
				}
				catch (Exception pEx)
				{
					LogError (pEx);

					lnkIndexFile.Visible = false;
				}
				finally
				{
					EnableBasicFeatures(true, false);
				}
			});
		}


		protected override void CancelCurrentOperation ()
		{
			btnToXLS.Enabled = true;

			_IndexMaker.Cancel ();

			EnableBasicFeatures (true, false);
		}

		#endregion

		
		#region ChecBox Events

		private void chkDetectBarcodes_CheckedChanged(object sender, EventArgs e)
		{
			if (chkDetectBarcodes.Checked)
			{
				chkBarcodeTypes.Enabled = true;
			}
			else
			{
				chkBarcodeTypes.Enabled = false;
			}
		}

		#endregion

		
	}
}
